package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.NumberUtils;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 * <新闻 - 新快网> 解析类 
 *  
 * @author KK
 *
 */
public class XkbNewsAnalyse implements AnalyseNews {

	
	public boolean isDetailPage(String url) {
		String[] regex={
				"http://news.xkb.com.cn/[a-z]*/[0-9]{4}/[0-9]{4}/[0-9]*.html",
				"http://news.xkb.com.cn/.*/.*/[0-9]+.html",
				};
		
		return RegexUtils.matchAny(url,regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {		

		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();
		
		String title=null;
		String content=null;
		Long date=null;
		String dateStr=null;
		String commnetNum=null;
		String clickNum=null;
		Document doc=Jsoup.parse(htmltxt);		
		
		title=doc.select("div.newsTitle h1").text();
		if(StringUtils.isBlank(title)){
			title=doc.select("title").text();
			title=StringUtils.substringBefore(title, "_");
		}
		dateStr=doc.select("div.newsTitle").text();
		content=HtmlCleaner.getContentHtml(url,doc.select("div.content"));

		
		date=DateUtils.matchDate(dateStr);
		if(date==null){
			date=JSoupUtils.matchDate(doc, "来源：");
		}
		
			NewsMeta news=new NewsMeta();
			news.setUrl(url);		
			news.setType(1);
			news.setTitle(StringUtils.trimSpace(title));
			news.setCommentNum(NumberUtils.parseInt(commnetNum));
			news.setClickNum(NumberUtils.parseInt(clickNum));
			news.setContent(StringUtils.trimSpace(content));
			news.setDate(date);

			String author=JSoupUtils.matchAuthor(doc, "来源：");
			news.setAuthor(author);
			
			return news;
	}
	
	

	public static void main(String[] args) {
		XkbNewsAnalyse a=new XkbNewsAnalyse();
		String url="http://news.xkb.com.cn/guangzhou/2014/0912/349426.html";
		System.out.println(a.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		NewsMeta parserHtml=a.parserHtml(meta);
		System.out.println(parserHtml.toString());
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}
	
	public boolean isNeedUpdate(){
		return false;
	}
}
